//
//  YSReadController.m
//  YSBookRead
//
//  Created by MOLBASE on 2018/11/7.
//  Copyright © 2018年 YangShen. All rights reserved.
//

#import "YSReadController.h"
#import "YSCoverViewController.h"
#import "YSReadTableViewController.h"
#import "YSReadPageController.h"
#import "YSReadOperation.h"
#import "YSReaderSetting.h"
#import "YSReadPageBGViewController.h"
#import "YSHUDManager.h"
#import "YSMenuViewController.h"
#import "YSChaperListViewController.h"
#import "YSDirectoryViewController.h"
#import "YSSummaryViewController.h"

@interface YSReadController () <UIPageViewControllerDataSource, UIPageViewControllerDelegate, YSCoverViewControllerDelegate, YSMenuViewControllerDelegate>
{
    UIStatusBarStyle _originalStatus;
    /// 用于区分正反面的值(固定)
    NSInteger _tempNumber;
    BOOL _pageIsAnimating;
}

/// 阅读操作对象
@property (nonatomic, strong) YSReadOperation *readOperation;

/// 翻页控制器(仿真)
@property (nonatomic, strong) UIPageViewController *pageViewController;
/// 翻页控制器(无效果, 平滑)
@property (nonatomic, strong) YSCoverViewController *coverViewController;
/// 翻页控制器(上下)
@property (nonatomic, strong) YSReadTableViewController *tableViewController;
/// 当前控制器
@property (nonatomic, strong) YSReadPageController *currentPageViewController;

/// 菜单控制器
@property (nonatomic, strong) YSMenuViewController *menuViewController;

/// 章节目录
//@property (nonatomic, strong) YSChaperListViewController *chaperListVC;

@end

@implementation YSReadController

- (instancetype)init {
    if (self = [super init]) {
        _originalStatus = [[UIApplication sharedApplication] statusBarStyle];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    if (_originalStatus == UIStatusBarStyleDefault) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_originalStatus == UIStatusBarStyleDefault) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapShowSetting:)]];

    // 初始化控制器操作对象
    self.readOperation = [[YSReadOperation alloc] init];

    self.menuViewController = [[YSMenuViewController alloc] init];
    self.menuViewController.isLocal = self.readBook.isLocalBook;
    [self addChildViewController:self.menuViewController];
    self.menuViewController.view.frame = self.view.bounds;
    self.menuViewController.delegate = self;
    [self.view addSubview:self.menuViewController.view];

    __weak typeof(self) weakSelf = self;

    [YSHUDManager showHUDMessage:@"加载小说中..."];
    [self.readOperation updateReadingBook:self.readBook completion:^{
        [YSHUDManager hide];
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.menuViewController.readOperation = strongSelf.readOperation;

        [strongSelf setupPageViewController:[strongSelf.readOperation getCurrentPageViewController]];
        // 更新阅读记录
        [strongSelf.readOperation updateReadRecordWithChapter:strongSelf.currentPageViewController.chapterContentModel.chapterIndex page:strongSelf.currentPageViewController.page];
    } failure:^(NSString *msg) {
        [YSHUDManager hide];
        [YSHUDManager showTipHUD:msg afterDelay:1];
    }];

    [[YSReaderSetting shareReaderSettings] setUpdateSettingBlock:^{
        YSBookChapterContentModel *chapterContent = self.readOperation.chapterContentList[self.readOperation.readRecord.readChapter];
        [chapterContent updateContentPaging];
        [self setupPageViewController:[self.readOperation getCurrentPageViewController]];
    }];

}

/// 创建翻页控制器 传入初始化显示控制器
- (void)setupPageViewController:(YSReadPageController *)displayController {
    if (!displayController) { return; }

    // 清理
    if (self.pageViewController) {
        [self.pageViewController.view removeFromSuperview];
        [self.pageViewController removeFromParentViewController];
        self.pageViewController = nil;
    }

    if (self.coverViewController) {
        [self.coverViewController.view removeFromSuperview];
        [self.coverViewController removeFromParentViewController];
        self.coverViewController = nil;
    }

    if (self.tableViewController) {
        [self.tableViewController.view removeFromSuperview];
        [self.tableViewController removeFromParentViewController];
        self.tableViewController = nil;
    }

    // 创建
    if ([[YSReaderSetting shareReaderSettings] pageStyle] == YSTurnPageStylePageCurl) { // 仿真
        _tempNumber = 1;

        // Option: 书脊位置
        self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:@{UIPageViewControllerOptionSpineLocationKey:@(UIPageViewControllerSpineLocationMin)}];
        self.pageViewController.dataSource = self;
        self.pageViewController.delegate = self;
        // 为了翻页背面的颜色使用
        self.pageViewController.doubleSided = YES;
        [self.view insertSubview:self.pageViewController.view atIndex:0];
        [self addChildViewController:self.pageViewController];

        [self.pageViewController setViewControllers:@[displayController] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    } else if ([[YSReaderSetting shareReaderSettings] pageStyle] == YSTurnPageStyleScroll ||
               [[YSReaderSetting shareReaderSettings] pageStyle] == YSTurnPageStyleNone) { // 无效果 平滑 上下
        self.coverViewController = [[YSCoverViewController alloc] init];
        self.coverViewController.delegate = self;
        [self.view insertSubview:self.coverViewController.view atIndex:0];
        [self addChildViewController:self.coverViewController];

        [self.coverViewController setViewController:displayController];
        if ([[YSReaderSetting shareReaderSettings] pageStyle] == YSTurnPageStyleNone) {
            self.coverViewController.openAnimate = NO;
        }
    } else { // 上下
        self.tableViewController = [[YSReadTableViewController alloc] init];
        self.tableViewController.readOperation = self.readOperation;
        [self.view insertSubview:self.tableViewController.view atIndex:0];
        [self addChildViewController:self.tableViewController];
    }

    self.currentPageViewController = displayController;
}

#pragma mark - YSCoverViewControllerDelegate
/// 上一页
- (UIViewController *)coverViewController:(YSCoverViewController *)coverViewController viewControllerBeforeCurrentViewController:(UIViewController *)currentViewController {
    return [self.readOperation getAbovePageViewController];
}

/// 下一页
- (UIViewController *)coverViewController:(YSCoverViewController *)coverViewController viewControllerAfterCurrentViewController:(UIViewController *)currentViewController {
    return [self.readOperation getBelowPageViewController];
}

- (void)coverViewController:(YSCoverViewController *)coverViewController willTransitionToPendingViewController:(UIViewController *)pendingViewController {
    // 隐藏menu
}

- (void)coverViewController:(YSCoverViewController *)coverViewController currentViewController:(UIViewController *)currentViewController didFinishAnimating:(BOOL)finished {
    // 记录
    self.currentPageViewController = (YSReadPageController *)currentViewController;

    // 更新阅读记录
    [self.readOperation updateReadRecordWithChapter:self.currentPageViewController.chapterContentModel.chapterIndex page:self.currentPageViewController.page];

    // 更新其他
    if (!self.currentPageViewController.chapterContentModel.haveCache) {
        [YSHUDManager showHUDMessage:@"章节加载中..."];
        __weak typeof(self) weakSelf = self;
        [self.readOperation getChapterContentWithChapter:self.readOperation.readRecord.readChapter needPadingContent:YES completion:^{
            [YSHUDManager hide];
            __strong typeof(weakSelf) sself = self;
            [sself setupPageViewController:[sself.readOperation getCurrentPageViewController]];
            [sself.readOperation autoLoadNextChapters:sself.readOperation.readRecord.readChapter+1];
        } failure:^(NSString *msg) {
            [YSHUDManager hide];
            [YSHUDManager showTipHUD:msg afterDelay:1];
        }];
    }
}


#pragma mark - UIPageViewControllerDataSource, UIPageViewControllerDelegate
/// 上一页
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    _tempNumber -= 1;


    NSLog(@"%@", viewController);

    if (labs(_tempNumber) % 2 == 0) { // 背面
        YSReadPageController *pageVC = [self.readOperation getAbovePageViewController];
        YSReadPageBGViewController *bgVC = [YSReadPageBGViewController readPageBGViewControllerWith:pageVC];
        return bgVC;
    } else {
        return [self.readOperation getAbovePageViewController];
    }
}

/// 下一页
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    _tempNumber += 1;


    if (labs(_tempNumber) % 2 == 0) { // 背面
        YSReadPageBGViewController *bgVC = [YSReadPageBGViewController readPageBGViewControllerWith:[self.readOperation getCurrentPageViewController]];
        return bgVC;
    } else {
        return [self.readOperation getBelowPageViewController];
    }
}

/// 准备切换
- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {

    YSReadPageController *pageVC = pageViewController.viewControllers.firstObject;

    // 隐藏menu

    // 更新阅读记录
}

/// 切换结果
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {

    if (!completed) {

        // 记录
        self.currentPageViewController = (YSReadPageController *)previousViewControllers.firstObject;

        // 更新阅读记录
        [self.readOperation updateReadRecordWithChapter:self.currentPageViewController.chapterContentModel.chapterIndex page:self.currentPageViewController.page];
    } else {

        // 记录
        self.currentPageViewController = (YSReadPageController *)pageViewController.viewControllers.firstObject;

        // 更新阅读记录
        [self.readOperation updateReadRecordWithChapter:self.currentPageViewController.chapterContentModel.chapterIndex page:self.currentPageViewController.page];

        // 更新其他
        if (!self.currentPageViewController.chapterContentModel.haveCache) {
            [YSHUDManager showHUDMessage:@"章节加载中..."];
            __weak typeof(self) weakSelf = self;
            [self.readOperation getChapterContentWithChapter:self.readOperation.readRecord.readChapter needPadingContent:YES completion:^{
                [YSHUDManager hide];
                __strong typeof(weakSelf) sself = self;
                [sself setupPageViewController:[sself.readOperation getCurrentPageViewController]];
                [sself.readOperation autoLoadNextChapters:sself.readOperation.readRecord.readChapter+1];
            } failure:^(NSString *msg) {
                [YSHUDManager hide];
                [YSHUDManager showTipHUD:msg afterDelay:1];
            }];
        }
    }
}


#pragma mark - YSMenuViewControllerDelegate
- (void)menuViewControllerDidClickChangeSourceButton:(YSMenuViewController *)menuViewController {
    YSSummaryViewController *summaryVC = [[YSSummaryViewController alloc] init];
    summaryVC.summaryM = self.readOperation.bookSummary;
    summaryVC.readOperation = self.readOperation;
    summaryVC.updateSelectSummary = ^(YSBookSummaryModel *summary) {
        [YSHUDManager showHUDMessage:@"正在换源..."];
        __weak typeof(self) weakSelf = self;
        [self.readOperation updateBookSummary:summary completion:^{
            [YSHUDManager hide];
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf setupPageViewController:[strongSelf.readOperation getCurrentPageViewController]];
        } failure:^(NSString *msg) {
            [YSHUDManager hide];
            [YSHUDManager showTipHUD:msg afterDelay:1];
        }];
    };
    [self presentViewController:summaryVC animated:YES completion:nil];
}

- (void)menuViewControllerDidClickReloadButton:(YSMenuViewController *)menuViewController {
    [self.readOperation updateReadRecordWithChapter:self.readOperation.readRecord.readChapter page:0];
    [YSHUDManager showHUDMessage:@"章节加载中..."];
    __weak typeof(self) weakSelf = self;
    [self.readOperation getChapterContentWithChapter:self.readOperation.readRecord.readChapter needPadingContent:YES completion:^{
        [YSHUDManager hide];
        __strong typeof(weakSelf) sself = self;
        [sself setupPageViewController:[sself.readOperation getCurrentPageViewController]];
    } failure:^(NSString *msg) {
        [YSHUDManager hide];
        [YSHUDManager showTipHUD:msg afterDelay:1];
    }];
}

- (void)menuViewControllerDidClickDirectoryButton:(YSMenuViewController *)menuViewController {
    YSDirectoryViewController *direVC = [[YSDirectoryViewController alloc] init];
    direVC.chaptersArr = self.readOperation.chapterContentList;
    direVC.readingChapter = self.readOperation.readRecord.readChapter;
    direVC.selectChapter = ^(NSInteger chapter) {
        [self.readOperation updateReadRecordWithChapter:chapter page:0];

        [YSHUDManager showHUDMessage:@"章节加载中..."];
        __weak typeof(self) weakSelf = self;
        [self.readOperation getChapterContentWithChapter:chapter needPadingContent:YES completion:^{
            [YSHUDManager hide];
            __strong typeof(weakSelf) sself = self;
            [sself setupPageViewController:[sself.readOperation getCurrentPageViewController]];
            [sself.readOperation autoLoadNextChapters:chapter+1];
        } failure:^(NSString *msg) {
            [YSHUDManager hide];
            [YSHUDManager showTipHUD:msg afterDelay:1];
        }];
    };
    [self presentViewController:direVC animated:YES completion:nil];
}

- (void)tapShowSetting:(UITapGestureRecognizer *)tap {
    CGPoint tapPoint = [tap locationInView:self.view];
    CGFloat width = [YSReaderSetting shareReaderSettings].pageStyle == YSTurnPageStyleUpAndDown ? [[UIScreen mainScreen] bounds].size.width : [[UIScreen mainScreen] bounds].size.width/3;
    CGRect rect = CGRectMake(([[UIScreen mainScreen] bounds].size.width - width)/2, 0, width, [[UIScreen mainScreen] bounds].size.height);
    if (CGRectContainsPoint(rect, tapPoint)) {
        [self.menuViewController showMenuView];
    }
}

@end
